<?php

/**
 * @Author: Mr.Mao
 * @Date:   2021-05-21 13:47:28
 * @Last Modified by:   Mr.Mao
 * @Last Modified time: 2021-05-27 16:34:06
 */
namespace app\weixin\controller\sys_admin;
use app\AdminController;
use app\weixin\model\WeixinVideoGoodsModel;
use app\weixin\model\WeixinVideoCateModel;
use app\weixin\model\WeixinVideoBrandModel;
use app\shop\model\GoodsModel;
use think\facade\Session;
/**
 * 视屏号商品管理
 * Class Index
 */
class VideoNumber extends AdminController
{
    public $goodsErrorCode = [];
    /*------------------------------------------------------ */
	//-- 优先执行
	/*------------------------------------------------------ */
	public function initialize(){
        parent::initialize();
        $this->Model = new WeixinVideoGoodsModel();
        $this->assign('edit_status',[0=>'初始值',1=>'编辑中',2=>'审核中',3=>'<font color="red">审核失败</font>',4=>'<font color="green">审核成功</font>']);
        $this->assign('status',[0=>'初始值',5=>'<font color="green">上架</font>',11=>'<font color="red">自主下架</font>',13=>'<font color="red">违规下架/风控系统下架</font>']);
        $this->goodsErrorCode = $this->Model->goodsErrorCode;
    }
    /**
     * [videoGoods 视屏号商品列表]
     */
    public function index()
    {

    	$this->getList(true);
    	return $this->fetch('index');
    }

    /*------------------------------------------------------ */
    //-- 获取列表
    //-- $runData boolean 是否返回模板
    /*------------------------------------------------------ */
    public function getList($runData = false) {
        $where = [];
        $p = input('p')?input('p'):1;
        $page_size = input("page_size/d",0);
        $session_page_size = Session::get('page_size') * 1;
        if ($page_size <= 1 ){
            if ($session_page_size <= 1) $session_page_size = 20;
            $page_size = $session_page_size;
        }elseif ($page_size != $session_page_size) Session::set('page_size',$page_size);


        $param = [];
        $param['page'] = $p;
        $param['page_size'] = $page_size;
        $res = $this->Model->getList($param);
        // print_r($res);
        if ($res['errcode'] > 0) {
            return $this->error($res['errmsg']);
        }

        $list = [];

        foreach ($res['spus'] as $key => $value) {
            $info = $this->Model->where('product_id',$value['product_id'])->find();
            $value['title'] = $info['title'];
            $value['out_product_id'] = $info['out_product_id'];
            $value['id'] = $info['id'];
            $list[] = $value;
        }        

        $data = [];
        $data['list'] = $list;
        $data['page'] = $param['page'];
        $data['page_size'] = $param['page_size'];
        $data['total_count'] = $res['total_num'];
        $data['page_count'] = ceil($res['total_num'] / $param['page_size']);
        
        $this->assign("data", $data);
        if ($runData == false){
            $data['content']= $this->fetch('list')->getContent();
            unset($data['list']);
            return $this->success('','',$data);
        }
        return true;
    }
    /**
     * [add 提交商品审核]
     */
    public function add()
    {
        $catList = (new WeixinVideoCateModel)->getRows();
        $brandList = (new WeixinVideoBrandModel)->getRows();

        if ($this->request->isPost()) {
            $post = input('post.');
            $data = $this->checkData($post);
            $data['add_time'] = time();
            $res = $this->Model->save($data);
            if ($res < 1) {
                $this->error('提交失败.');
            }
            return $this->success('提交成功.',url('index'));
        }


        $this->assign('catList',$catList);
        $this->assign('brandList',$brandList);
    	return $this->fetch('add');
    }

    /*------------------------------------------------------ */
    //-- 验证商品数据
    /*------------------------------------------------------ */
    public function checkData($row = [],$is_update = false)
    {
        $goods_id = $row['shop_goods_id'];
        if ($goods_id < 1) {
            return $this->error('传参错误.');
        }

        $GoodsModel = new GoodsModel();
        $goods = $GoodsModel->info($goods_id);
        // print_r($goods);
        if (empty($goods)) {
            return $this->error('商品不存在.');
        }

        $data = [];

        $data['out_product_id'] = $goods['goods_id'];
        $data['title'] = $goods['goods_name'];
        $data['path'] = substr(config('config.xcx_goods_path'),1) . $goods['goods_id'];

        $head_img = [];

        foreach ($goods['imgList'] as $key => $value) {
            $head_img[] = config('config.host_path') . $value['goods_img'];
        }
        $data['head_img'] = $head_img;
        $qualification_pics = [];
        foreach ($row['images']['path'] as $url) {
            $qualification_pics[] = config('config.host_path') . $url;
        }
        $data['qualification_pics'] = $qualification_pics;

        $data['desc_info']['desc'] = $goods['m_goods_desc'];
        $data['desc_info']['imgs'] = '';
        $data['third_cat_id'] = $row['third_cat_id'];
        $data['brand_id'] = $row['brand_id'];
        $data['info_version'] = '1.0.0';
        $data['skus'] = [];
        $skus = [];
        if ($goods['is_spec'] == 1) {
            if (empty($row['sku_ids'])) return $this->error('请选择商品规格.');

            foreach ($row['sku_ids'] as $sku_id) {
                $sku = [];
                $skuInfo = $goods['sub_goods'][$sku_id];
                $sku['out_product_id'] = $goods['goods_id'];
                $sku['out_sku_id'] = $skuInfo['sku_id'];
                foreach ($goods['imgSkuList'] as $v) {
                    if ($v['sku_val'] == $skuInfo['sku_val']) {
                        $sku['thumb_img'] = config('config.host_path') .$v['goods_img'];
                    }
                }
                $sku['market_price'] = $skuInfo['market_price'];
                $sku['sale_price'] = $skuInfo['sale_price'];
                $sku['stock_num'] = $skuInfo['goods_number'];
                $sku['sku_code'] = $skuInfo['goods_sn'];
                $sku['barcode'] = '';
                $sku['sku_attrs'] = [];
                $sku['sku_attrs'][0]['attr_key'] = '';
                $sku['sku_attrs'][0]['attr_value'] = '';
                $skus[] = $sku;                 
            }
            $data['skus'] = $skus;
        }else{
            $data['skus'][0]['market_price'] = $goods['market_price'];
            $data['skus'][0]['sale_price'] = $goods['sale_price'];
            $data['skus'][0]['stock_num'] = $goods['goods_number'];
            $data['skus'][0]['out_product_id'] = $goods['goods_id'];
            $data['skus'][0]['out_sku_id'] = 0;
            $data['skus'][0]['sku_code'] = $goods['goods_sn'];
            $data['skus'][0]['barcode'] = '';
            $data['skus'][0]['sku_attrs'][0]['attr_key'] = '';
            $data['skus'][0]['sku_attrs'][0]['attr_value'] = '';
        }

        if ($is_update == false) {
            $res = $this->Model->add($data);
        }else{
            $res = $this->Model->updateGoods($data);
        }
        if ($res['errcode'] > 0) {
            return $this->error($this->goodsErrorCode[$res['errcode']]);
        }

        $data['product_id'] = $res['data']['product_id'];
        $data['create_time'] = strtotime($res['data']['create_time']);
        $data['skus'] = json_encode($data['skus']);
        $data['head_img'] = join(',',$data['head_img']);
        $data['qualification_pics'] = join(',',$data['qualification_pics']);
        $data['desc_info'] = json_encode($data['desc_info']);
        $data['status'] = 0;
        return $data;
    }
    /**
     * [edit 编辑商品]
     */
    public function edit()
    {
        $id = input('id/d');
        if ($id < 1) {
            return $this->error('传参错误');
        }

        $type = input('type',1,'intval');
        if ($type == 1) {
            $post = input('post.');
            $data = $this->checkData($post,true);
            $data['update_time'] = time();
            $res = $this->Model->where('id',$id)->update($data);
            if ($res < 1) {
                $this->error('提交失败.');
            }
            return $this->success('提交成功.',url('index'));
        }else{
            $product_id = $this->Model->where('id',$id)->value('product_id');
            $data = [];
            $data['product_id'] = $product_id;
            $res = $this->Model->delAudit($data);
            if ($res['errcode'] > 0) {
                return $this->error($res['errmsg']);
            }
            return $this->success('处理成功.',url('index'));
        }
    }

    /**
     * [info 商品详情]
     */
    public function info()
    {
        $id = input('id');
        if ($id < 1) {
            return $this->error('传参错误.');
        }
        $GoodsModel = new GoodsModel();
        $info = $this->Model->find($id);
        if (empty($info)) {
            return $this->error('商品不存在.');
        }
        $info = $info->toArray();

        $data = [];
        $data['product_id'] = $info['product_id'];

        $res = $this->Model->info($data);
        if ($res['errcode'] > 0) {
            return $this->error($res['errmsg']);
        }

        $info['spu'] = $res['spu'];

        $goods = (new GoodsModel)->info($info['out_product_id']);

        $skus = json_decode($info['skus'],true);
        unset($info['skus']);
        if ($goods['is_spec'] == 1) {
            $info['skus'] = [];
            foreach ($skus as $sku) {
                $info['skus'][$sku['out_sku_id']] = $sku;
            }
        }else{
            $info['market_price'] = $skus[0]['market_price'];
            $info['sale_price'] = $skus[0]['sale_price'];
            $info['stock_num'] = $skus[0]['stock_num'];
        }

        if (empty($info['qualification_pics']) == false) {
            $info['qualification_pics'] = explode(',', $info['qualification_pics']);
        }
        $catList = (new WeixinVideoCateModel)->getRows();
        $brandList = (new WeixinVideoBrandModel)->getRows();
        $this->assign('catList',$catList);
        $this->assign('row',$info);
        $this->assign('brandList',$brandList);
        $this->assign('goods',$goods);
        return $this->fetch('info');
    }
    /**
     * [delisting 下架商品]
     */
    public function delisting()
    {
        $product_id = input('product_id');
        if (empty($product_id)) {
            return $this->error('传参错误.');
        }
        $data = [];
        $data['product_id'] = $product_id;
        $res = $this->Model->delisting($data);
        if ($res['errcode'] > 0) {
            return $this->error($res['errmsg']);
        }
        return $this->success('商品已下架','window.location.reload()');
    }

    /**
     * [delisting 下架商品]
     */
    public function listing()
    {
        $product_id = input('product_id');
        if (empty($product_id)) {
            return $this->error('传参错误.');
        }
        $data = [];
        $data['product_id'] = $product_id;
        $res = $this->Model->listing($data);
        if ($res['errcode'] > 0) {
            return $this->error($res['errmsg']);
        }
        return $this->success('商品已上架','window.location.reload()');
    }
    /**
     * [delSpu 删除商品]
     */
    public function delSpu()
    {
        $product_id = input('product_id');
        if (empty($product_id)) {
            return $this->error('传参错误.');
        }
        $data = [];
        $data['product_id'] = $product_id;
        $res = $this->Model->delSpu($data);
        if ($res['errcode'] > 0) {
            return $this->error($res['errmsg']);
        }
        $this->Model->where('product_id',$product_id)->delete();
        return $this->success('商品已删除','window.location.reload()');
    }

    /*------------------------------------------------------ */
    //-- 上传资质图片
    /*------------------------------------------------------ */
    public function uploadImg(){
        $this->returnJson = true;//统一返回json
        $result = $this->_upload($_FILES['file'],'qualification_pics/');
        if ($result['error']) {
            return $this->error('上传失败，请重试.');
        }
        $file_url = str_replace('./','/',$result['info'][0]['savepath'].$result['info'][0]['savename']);
        $data['image'] = array('thumbnail'=>$file_url,'path'=>$file_url);
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 删除图片
    /*------------------------------------------------------ */
    public function removeImg() {
        $file = input('post.url','','trim');
        unlink('.'.$file);
        return $this->success('删除成功.');
    }
}
